package com.android.ddfafu.domian;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;

import com.android.ddfafu.utils.BitmapUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * @description 用于存取bitmap
 */
public class ImageData {
    private SharedPreferences sp_img;
    private SharedPreferences sp_user;
    private List<Bitmap> bitmapList;
    private List<String> bitmapPathList;
    private String usernameSub;

    public ImageData(Context context) {
        bitmapList = new ArrayList<Bitmap>();
        bitmapPathList = new ArrayList<>();
        new Thread(() -> {
            while (true) {
                addBitmapToList(context);
            }
        }).start();
    }

    public void addBitmapToList(Context context) {
        try {
            Thread.sleep(200);
            sp_img = context.getSharedPreferences("userImages", Context.MODE_WORLD_WRITEABLE);
            sp_user = context.getSharedPreferences("userData", Context.MODE_WORLD_WRITEABLE);
            usernameSub = sp_user.getString("USERNAME", "").replace("@", "").replace(".", "");
            Set<String> image_path_set = sp_img.getStringSet(usernameSub, null);
            List<String> image_path_list = new ArrayList<>(image_path_set);
            //String usernameSub = sp_user.getString("USERNAME", "").replace("@", "").replace(".", "");
            System.out.println("image_path_list.size = " + image_path_list.size());

            if (image_path_set.size() != bitmapList.size()) {
                bitmapList.clear();
                bitmapPathList.clear();
                Iterator<String> iterator = image_path_set.iterator();
                int index = 0;
                while (index < image_path_set.size() - bitmapList.size()) {
                    String path = iterator.next();
                    //path.substring(27,path.indexOf("com"));
                        File file = new File(path);
                        if (file.exists()) {
                            Uri uri = Uri.fromFile(file);
                            Bitmap bitmap = BitmapUtil.getBitmapFromUri(context, uri);
//                    Bitmap bitmap = BitmapFactory.decodeStream(context.getContentResolver().openInputStream(uri));
                            bitmapList.add(bitmap);
                            bitmapPathList.add(path);
                        }

                }

            }
        } catch (Exception e) {
        }
    }

    public List<Bitmap> getBitmapList() {
        return bitmapList;
    }

    public List<String> getBitmapPathList() {
        return bitmapPathList;
    }
}
